package com.ouroboroswiki.core.content.markup.processor;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import com.ouroboroswiki.core.Content;
import com.ouroboroswiki.core.ContentPath;
import com.ouroboroswiki.core.ContentRepository;
import com.ouroboroswiki.core.ContentValidationResult;
import com.ouroboroswiki.core.Version;

public class URLContentMarkupHandler extends AbstractExternalContentMarkupHandler implements MarkupHandler {
		
	private static final Logger log = Logger.getLogger( URLContentMarkupHandler.class.getName() );
	
	public static final String ELEMENT_VERSION 	= "version";
	
	private String linkRoot;
	private ContentRepository source;
	
	public URLContentMarkupHandler(String linkRoot) {
		this.linkRoot = linkRoot;
	}
	
	public ContentRepository getSource() {
		return source;
	}

	public void setSource(ContentRepository source) {
		this.source = source;
	}

	@Override
	public List<Node> replace(Object principal, Element e, Document parent,
			Map<String, Content> childContent, ContentPath currentPath,
			Version version, Collection<ContentValidationResult> validations, Map<String, Object> properties) throws IOException {
		ContentPath linkPath = buildPathFromContext(e, currentPath);
		String id = e.getAttribute(ATTRIBUTE_ID);
		try {
			Content urlContent = source.getContent(principal, linkPath, version, properties);
			childContent.put(id, urlContent);
		} catch( Exception ex ) {
			validations.add(
					new ContentValidationResult(
							ContentValidationResult.Level.Error, 
							"error loading "+id,
							ex
			));
		}
		Node url = parent.createTextNode(linkRoot + linkPath.toString());
		return (List<Node>)Arrays.asList(url);
	}
}
